//
//  AppDelegate.swift
//  YDOAProduct
//
//  Created by YDWY on 2017/5/17.
//  Copyright © 2017年 Allen. All rights reserved.
//

import UIKit
import UserNotifications
import IQKeyboardManagerSwift

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate
 {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
     
        //键盘遮挡输入框
        IQKeyboardManager.sharedManager().enable = true
        
        
        //极光推送
        let entity = JPUSHRegisterEntity();
        entity.types = Int(JPAuthorizationOptions.alert.rawValue) |  Int(JPAuthorizationOptions.sound.rawValue) |  Int(JPAuthorizationOptions.badge.rawValue);
        JPUSHService.register(forRemoteNotificationConfig: entity, delegate: self);
        // 注册极光推送
        JPUSHService.setup(withOption: launchOptions, appKey: "840744789e492a953791a38e", channel:"Publish channel" , apsForProduction: false);
        // 获取推送消息
        let remote = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? Dictionary<String,Any>;
        // 如果remote不为空，就代表应用在未打开的时候收到了推送消息
        if remote != nil {
            // 收到推送消息实现的方法
            self.perform(#selector(receivePush), with: remote, afterDelay: 1.0);
        }

        //腾讯信鸽推送
      //打开 Debug 模式以后可以在终端看到详细的信鸽 Debug 信息.方便定位问题
        let  set =  XGSetting.getInstance() as? XGSetting
        set?.enableDebug(true)
        
        XGPush.startApp(2200259182, appKey: "IM67J2JL7H3D")
        XGPush.isPush { (isPushOn) in
            NSLog("[XGDemo] Push Is %@",isPushOn ? "ON" : "OFF")
        }
        registerAPNs()
        
//        XGPush.handleLaunching(launchOptions!, successCallback: { 
//            print("[XGDemo] Handle launching success")
//        }) { 
//            print("[XGDemo] Handle launching error")
//        }
        
        
        
        
        
        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }


}


//APNs 推送相关
extension AppDelegate : UNUserNotificationCenterDelegate{

    fileprivate func registerAPNs (){
        print("设备的系统\(UIDevice.current.systemVersion)")
        let  sysVer = (UIDevice.current.systemVersion as NSString).floatValue
        
       // guard let sysVer =  NumberFormatter().number(from:UIDevice.current.systemVersion) else { return }
        //guard let sysVer = Double() else {return }
        if (sysVer >= 10) {
            // iOS 10
            registerPush10()
        } else if (sysVer >= 8) {
            // iOS 8-9
            registerPush8to9()
        } else {
            // before iOS 8
            registerPushBefore8()
        }
        
        
    }
    
    
    private func registerPush10(){
        if #available(iOS 10.0, *) {
            let  center = UNUserNotificationCenter.current()
            center.delegate = self
            
            center .requestAuthorization(options: [UNAuthorizationOptions.badge,.sound,.alert]) { (granted, error) in
                if granted != false {
                    center.getNotificationSettings(completionHandler: { (settings) in
                        print(settings)
                    })
                }
            }
            UIApplication.shared.registerForRemoteNotifications()

        } else {
            // Fallback on earlier versions
             print("失败")
        }
        
    }
    

    private func registerPush8to9(){
        
      
        let  seting =  UIUserNotificationSettings(types: [.alert,.badge,.sound], categories: nil)
        UIApplication.shared.registerUserNotificationSettings(seting)
        UIApplication.shared.registerForRemoteNotifications()
    }
    
    private func registerPushBefore8(){
       //   UIApplication.shared.registerForRemoteNotifications(matching: [.alert,.badge,.sound])
    }
    
    
    
 
    //// App 在前台弹通知需要调用这个接口
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
        let request = notification.request
        let content = request.content
        
        _ = content.badge
        _ = content.body
        _ = content.sound
        _ = content.subtitle
        _ = content.title
        
        if notification.request.trigger!.isKind(of: UNPushNotificationTrigger.self) {
            print("远程通知:\(userInfo)")
        } else {
            print("本地通知")
        }
        completionHandler([.alert,.badge,.sound])
        
    }
    
    // 通知的点击事件
    // iOS 10 新增 API
    // iOS 10 会走新 API, iOS 10 以前会走到老 API
    // App 用户点击通知的回调
    // 无论本地推送还是远程推送都会走这个回调
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        let request = response.notification.request
        let content = request.content
        
        _ = content.badge
        _ = content.body
        _ = content.sound
        _ = content.subtitle
        _ = content.title
        
        if response.notification.request.trigger!.isKind(of: UNPushNotificationTrigger.self) {
            print("远程通知:\(userInfo)")
        } else {
            print("本地通知")
        }
        
        XGPush .handleReceiveNotification(response.notification.request.content.userInfo, successCallback: { 
             NSLog("[XGDemo] Handle receive success");
        }) { 
             NSLog("[XGDemo] Handle receive error");
        }
        
        
        completionHandler()
    }
    
 
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        
        
        /// Required - 注册 DeviceToken
        //极光
       JPUSHService.registerDeviceToken(deviceToken)
        
        
        //信鸽
        let deviceTokenStr = XGPush.registerDevice(deviceToken, successCallback: { 
              NSLog("[XGDemo] register push success")
        }) { 
             NSLog("[XGDemo] register push error")
        }
        NSLog("[XGDemo] device token is %@", deviceTokenStr ?? "设备号获取失败")
    }
    
    
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        NSLog("[XGDemo] register APNS fail.\n[XGDemo] reason : %@", error.localizedDescription)
    }
  
    
    
    /**
     收到通知的回调
     @param application  UIApplication 实例
     @param userInfo 推送时指定的参数
     */
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
        NSLog("[XGDemo] receive Notification")
        XGPush.handleReceiveNotification(userInfo, successCallback: { 
            print("获取的结果\(userInfo)")
        }) { 
            print("获取结果失败")
        }
        
    }
    
  
    
    
    /**
     收到静默推送的回调
     
     @param application  UIApplication 实例
     @param userInfo 推送时指定的参数
     @param completionHandler 完成回调
     */
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        NSLog("[XGDemo] receive slient Notification")
        NSLog("[XGDemo] userinfo %@", userInfo)
        //信鸽
        XGPush.handleReceiveNotification(userInfo, successCallback: {
            print("获取的结果\(userInfo)")
        }) {
            print("获取结果失败")
        }
        //极光
        JPUSHService.handleRemoteNotification(userInfo);
        completionHandler(UIBackgroundFetchResult.newData);
    }
    
    

}



//极光推送
extension AppDelegate:JPUSHRegisterDelegate{
    // MARK: -JPUSHRegisterDelegate
    // iOS 10.x 需要
    @available(iOS 10.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!, withCompletionHandler completionHandler: ((Int) -> Void)!) {
        
        let userInfo = notification.request.content.userInfo;
        if notification.request.trigger is UNPushNotificationTrigger {
            JPUSHService.handleRemoteNotification(userInfo);
        }
        completionHandler(Int(UNNotificationPresentationOptions.alert.rawValue))
    }
    @available(iOS 10.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> Void)!) {
        
        let userInfo = response.notification.request.content.userInfo;
        if response.notification.request.trigger is UNPushNotificationTrigger {
            JPUSHService.handleRemoteNotification(userInfo);
        }
        completionHandler();
        // 应用打开的时候收到推送消息
//        NotificationCenter.default.post(name: NSNotification.Name(rawValue: NotificationName_ReceivePush), object: NotificationObject_Sueecess, userInfo: userInfo)
    }
    
  
    // 接收到推送实现的方法
    func receivePush(_ userInfo : Dictionary<String,Any>) {
        // 角标变0
        UIApplication.shared.applicationIconBadgeNumber = 0;
        // 剩下的根据需要自定义
        //self.tabBarVC?.selectedIndex = 0;
        //NotificationCenter.default.post(name: NSNotification.Name(rawValue: NotificationName_ReceivePush), object: NotificationObject_Sueecess, userInfo: userInfo)
    }
}




